package cn.bone.rss.service;

import cn.bone.rss.bean.NewsDo;
import cn.bone.rss.dao.RssDao;
import com.aliyun.oss.OSSClient;
import org.apache.commons.lang.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.*;
import java.util.List;
import java.util.Locale;

/**
 * Created by superbone on 2017/3/13.
 */
@Service
public class RssService {

    @Resource
    private RssDao rssDao;

    private Logger logger = LoggerFactory.getLogger("rss");

    private String channelTitle = "东楚风s";
    private String channelDescription = "东楚风s，东楚晚报旗下客户端，提供黄石新闻、服务与资讯。";
    private String channelLink = "http://119.97.167.67:8188/";
    private String dir = "E:/soft/apache-tomcat-7.0.62-dcw-app/webapps/appDownload/";
    private String fileName = "rss.xml";
    private String createFileName = "temp.xml";



    @Scheduled(cron="0 0 0/1 * * *")
    public void execute(){

        logger.info("执行写rss文件操作");

        List<NewsDo> list = rssDao.list(500);

        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File createFile = new File(dir+createFileName);
        FastDateFormat fdf = FastDateFormat.getInstance("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);

        try(OutputStream os = new FileOutputStream(createFile)) {
            XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
            XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(os,"UTF-8");
            writer.writeStartDocument("utf-8","1.0");
            // <rss version=2.0>
            writer.writeStartElement("rss");
            writer.writeAttribute("version", "2.0");

            // <channel>
            writer.writeStartElement("channel");

            // <title></title>
            writer.writeStartElement("title");
            writer.writeCharacters(channelTitle);
            writer.writeEndElement();

            // <description></description>
            writer.writeStartElement("description");
            writer.writeCharacters(channelDescription);
            writer.writeEndElement();

            // <channelLink></channelLink>
            writer.writeStartElement("channelLink");
            writer.writeCharacters(channelLink);
            writer.writeEndElement();

            for (NewsDo news : list) {

                logger.info("写新闻<"+news.getId()+">到rss");
                // <item>
                writer.writeStartElement("item");
                // <title>
                writer.writeStartElement("title");
                writer.writeCData(news.getTitle());
                writer.writeEndElement();

                // <link>
                writer.writeStartElement("link");
                writer.writeCharacters(news.getLink());
                writer.writeEndElement();

                // <description>
                writer.writeStartElement("description");
                writer.writeCData(news.getDescription());
                writer.writeEndElement();

                // <source>
                writer.writeStartElement("source");
                writer.writeCharacters(news.getSource());
                writer.writeEndElement();

                // <pubDate>
                writer.writeStartElement("pubDate");
                writer.writeCharacters(fdf.format(news.getPubDate()));
                writer.writeEndElement();

                writer.writeEndElement();
            }
            writer.writeEndElement();
            writer.writeEndElement();
            writer.writeEndDocument();

            writer.flush();
            writer.close();

        } catch (XMLStreamException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(createFile.exists()){
            logger.info("rss文件创建成功");
            String rssFileName = dir+fileName;
            File targetFile = new File(rssFileName);
            if(targetFile.exists()){
                targetFile.delete();
            }
            createFile.renameTo(targetFile);
            uploadOSS(rssFileName);
        }



    }

    // 阿里OSS参数
    private static final String acessKey = "LTAILzzIkDYJWvQ8";
    private static final String secretKey = "qYvukYl5u99MMSwyyZTXymYQ1AiAVr";
    // 文件上传地址
    private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 空间名称
    private static final String bucketName = "xmd";
    // 图片空间名称
    private static final String imgBucket = "http://xmd.img-cn-hangzhou.aliyuncs.com";
    //文件空间地址
    private static final String fileBucket = "http://xmd.oss-cn-hangzhou.aliyuncs.com";


    /**
     * 上传文件到阿里云OSS
     * @param fileName
     */
    private void uploadOSS(String fileName){

        File file = new File(fileName);
        if(!file.exists()){
            return;
        }
        logger.info("上传文件到阿里OSS");

        //初始化OSS参数
        OSSClient client = new OSSClient(endpoint, acessKey,secretKey);
        String key = "rss.xml";
        client.putObject(bucketName,key,file);
        client.shutdown();
    }
}
